/*************************************************************************
 *  Copyright © 2023-2030 FXB CO.,LTD. All rights reserved.
 *------------------------------------------------------------------------
 *  公司：DefaultCompany
 *  项目：CustomBuildProcess
 *  文件：LogInfoHtmlOutput.cs
 *  作者：Administrator
 *  日期：2025/6/14 22:25:27
 *  功能：Nothing
*************************************************************************/

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace CustomBuildProcess.Editor
{
    public class LogInfoHtmlOutput
    {
        public static async Task WriteBuildLogToHtml(BuildInfo lastBuildInfo, BuildConfigItem buildConfigItem)
        {
            string htmlLogTemplatePath = PathManager.BuildLogHtmlTemplatePath;
            string LogItemTemplatePath = PathManager.LogItemHtmlTemplatePath;

            string htmlLogPath = PathManager.BuildLogHtmlPath;

            try
            {
                // 准备完整的 HTML 内容
                string existingHtml;
                if (!File.Exists(htmlLogPath))
                    existingHtml = BuildHtmlHeader(htmlLogTemplatePath);
                else
                    existingHtml = File.ReadAllText(htmlLogPath);

                string logHtml = BuildLogHtml(LogItemTemplatePath, lastBuildInfo, buildConfigItem);

                string contentTag = $"<div class=\"content\">";

                // 查找该标签在 HTML 中的位置
                int contentStartIndex = existingHtml.IndexOf(contentTag, StringComparison.Ordinal);

                if (contentStartIndex >= 0)
                {
                    int contentEndIndex = contentStartIndex + contentTag.Length;

                    existingHtml = existingHtml.Insert(contentEndIndex, "\n" + logHtml);
                }
                else
                {
                    int bodyStartIndex = existingHtml.IndexOf("</body>", StringComparison.Ordinal);
                    if (bodyStartIndex >= 0)
                    {
                        existingHtml = existingHtml.Insert(bodyStartIndex, "\n" + logHtml);
                    }
                }

                existingHtml = RemoveEmptyLines(existingHtml);

                // 写入文件
                using (StreamWriter writer = new StreamWriter(htmlLogPath, false, Encoding.UTF8))
                {
                    await writer.WriteAsync(existingHtml);
                }

                Debug.Log($"Build log appended to HTML at: {htmlLogPath}");

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogError($"Failed to append HTML build log: {e.Message}");
            }
        }

        /// <summary>
        /// 构建HTML模板
        /// </summary>
        /// <returns></returns>
        public static string BuildHtmlHeader(string templatePath)
        {
            string htmlTemplate = File.ReadAllText(templatePath);
            htmlTemplate = htmlTemplate.Replace("_BUILDLOGNAME_", $"Build Log");
            return htmlTemplate;
        }

        /// <summary>
        /// 根据版本号删除对应的构建日志块
        /// </summary>
        /// <param name="versionToDelete">要删除的版本号（如 "1.0.0"）</param>
        public static async Task DeleteBuildLogByVersion(string version, string type)
        {
            string htmlLogPath = PathManager.BuildLogHtmlPath;

            if (!File.Exists(htmlLogPath))
            {
                Debug.Log("The HTML log file does not exist");
                return;
            }

            try
            {
                string htmlContent = File.ReadAllText(htmlLogPath);

                // 构造正则表达式：匹配带有指定版本号的 log-container 块
                string pattern = $"<div class=\"log-container\" data-version=\"{Regex.Escape(version)}\" data-type=\"{Regex.Escape(type)}\">[\\s\\S]*?</div>[\\r\\n\\s]*<hr */*>";
                var regex = new Regex(pattern, RegexOptions.Multiline);

                if (!regex.IsMatch(htmlContent))
                {
                    Debug.LogWarning($"Build log with version {htmlLogPath} not found");
                    return;
                }

                // 删除匹配的区块
                htmlContent = regex.Replace(htmlContent, "");

                htmlContent = RemoveEmptyLines(htmlContent);

                // 写回文件
                using (StreamWriter writer = new StreamWriter(htmlLogPath, false, Encoding.UTF8))
                {
                    await writer.WriteAsync(htmlContent);
                }

                Debug.Log($"The build log for {version} ({type}) has been deleted");

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogError($"Failed to delete {version} ({type}) build log: {e.Message}");
            }
        }

        public static string BuildLogHtml(string templatePath, BuildInfo lastBuildInfo, BuildConfigItem buildConfigItem)
        {
            string htmlTemplate = File.ReadAllText(templatePath);

            htmlTemplate = htmlTemplate.Replace("_DATA-VERSION_", $"{lastBuildInfo.version}");
            htmlTemplate = htmlTemplate.Replace("_DATA_TYPE_", $"{lastBuildInfo.type}");
            htmlTemplate = htmlTemplate.Replace("_BUILDTIME_", $"Build Time: {lastBuildInfo.buildTime}");
            htmlTemplate = htmlTemplate.Replace("_PLATFORM_", $" {buildConfigItem.GetPlatform(lastBuildInfo.platform)}");
            htmlTemplate = htmlTemplate.Replace("_APPID_", $" {lastBuildInfo.appID}");
            htmlTemplate = htmlTemplate.Replace("_FEATURE_", $" {buildConfigItem.GetFeature(lastBuildInfo.feature)}");
            htmlTemplate = htmlTemplate.Replace("_MODEL_", $" {buildConfigItem.GetModel(lastBuildInfo.model)}");
            htmlTemplate = htmlTemplate.Replace("_LANGUAGE_", $" {buildConfigItem.GetLanguage(lastBuildInfo.language)}");
            htmlTemplate = htmlTemplate.Replace("_TYPE_", $" {buildConfigItem.GetType(lastBuildInfo.type)}");
            htmlTemplate = htmlTemplate.Replace("_COMPANYNAME_", $" {lastBuildInfo.companyName}");
            htmlTemplate = htmlTemplate.Replace("_PRODUCTNAME_", $" {lastBuildInfo.productName}");
            htmlTemplate = htmlTemplate.Replace("_VERSION_", $" V{lastBuildInfo.version}");
            htmlTemplate = htmlTemplate.Replace("_BUILDLOG_", $"{"\n" + lastBuildInfo.log + "\n"}");

            return htmlTemplate;
        }


        /// <summary>
        /// 去除所有空白行（即整行只有空格、Tab、换行符的行）
        /// </summary>
        public static string RemoveEmptyLines(string input)
        {
            // 匹配以任意空白字符开头和结尾的行，并移除它们
            return Regex.Replace(input, @"^\s+$\n?", "\n",
                RegexOptions.Multiline |
                RegexOptions.Compiled);
        }
    }
}